package controller

import (
	"errors"
	"workflow/config"
	"workflow/controller/request"
	"workflow/service"

	"github.com/gin-gonic/gin"
)

func CreateWorkflowController(c *gin.Context) {
	var req request.CreateWorkflowRequest
	var err error

	err = c.BindJSON(&req)
	if err != nil {
		SendError(c, err)
		return
	}
	err = service.CreateWorkflow(req.Name, req.ProjectID, req.DSL)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, nil)
}

func TriggerWorkflowController(c *gin.Context) {
	id, exists := c.GetQuery("id")
	if !exists {
		SendError(c, errors.New("没有参数 id"))
		return
	}
	// 启动一个workflow
	trigger, err := service.WebTrigger(c, id)
	if err != nil {
		SendError(c, err)
		return
	}

	config.TriggerChannel <- trigger.ID

	SendData(c, nil)
}

func GetWorkflowController(c *gin.Context) {
	id, ok := c.GetQuery("id")
	if !ok {
		panic(ok)
	}

	workflow, err := service.FindWorkflow(id)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, workflow)
}
